package org.dromara.company.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.dromara.common.ratelimiter.annotation.RateLimiter;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.LinkedHashMap;

/**
 * 短信操作处理
 *
 * @author Lion Li
 */
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class BillCaptchaController {

    /**
     * 短信验证码
     *
     * @param phonenumber 用户手机号
     */
    @RateLimiter(key = "#phonenumber", time = 60, count = 1)
    @GetMapping("/Bill/sms/code")
    public R<Void> smsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
        // 验证手机号
        if (!Validator.isMobile(phonenumber)) {
            throw new ServiceException("手机号码格式错误！");
        }

        // 生成验证码以及缓存的key
        String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
        String code = RandomUtil.randomNumbers(4);
//        if (RedisUtils.hasKey(key)) {
//            throw new ServiceException("获取短信过于频繁，请稍后再获取！");
//        }
        // 存入缓存
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));

        // 发送短信
        Dict dict = Dict.create()
            .set("code", code)
            .set("corpId", "JX008282")
            .set("pwd", "123456");
        try {
            sendSms(phonenumber, dict);
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return R.fail("验证码短信发送异常");
        }
        return R.ok(code);
    }

    public void sendSms(String phonenumber, Dict dict) throws Exception {
        // 短信待集成
        String corpId = dict.getStr("corpId"); //账户名
        String pwd = dict.getStr("pwd"); //密码
        String send_content = "您好，您的验证码为" + dict.getStr("code") + "，验证码两分钟内有效，请勿向他人泄露！【扫贝信息科技】";

        String content = URLEncoder.encode(send_content, "GBK");
        log.info("短信内容：{}", send_content);

        URL url = new URL("https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID=" + corpId + "&Pwd=" + pwd + "&Mobile=" + phonenumber + "&Content=" + content + "&Cell=&SendTime=");
        BufferedReader in = null;
        String inputLine = "";
        String message = "";
        try {
            log.info("开始发送短信手机号码为 ：{}", phonenumber);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((inputLine = in.readLine()) != null) {
                message += inputLine;
            }
        } catch (Exception e) {
            log.error("网络异常,发送短信失败！");
            e.printStackTrace();
            inputLine = "err";
        }
        log.info("结束发送短信返回值：  " + message);
    }
}
